<template>
    <div class="modal-form">
        <a-modal
            :visible.sync="visible"
            :title="title"
            :cancelText="cancelText"
            :okText="okText"
            :width="width"
            :closable="closable"
            :connfirm-loading="loading"
            @ok="onClickOk"
            @cancel="onClickCancel"
        >
            <a-form-model
                ref="form"
                :model="form"
                :rules="rules"
                :label-col="{ span: labelSpan }"
                :wrapper-col="{ span: wrapperSpan }"
                :layout="layout"
            >
                <div v-for="(items, key, index) in columns" :key="index">
                    <a-form-model-item
                        :label="items.label"
                        :prop="key"
                        v-if="!items.show"
                        :class="{ editor: items.type === 'editor' }"
                    >
                        <a-input
                            v-if="items.type === 'input'"
                            v-model="form[key]"
                            :placeholder="`请输入${items.label}`"
                            :type="items.inputType || 'text'"
                            autosize
                        />
                        <div v-if="items.type === 'inputArray'">
                            <div v-for="(vv, i) in form[key]" :key="i" class="input-array">
                                <a-input
                                    v-model="form[key][i]"
                                    :placeholder="`请输入${items.label}`"
                                    :type="items.inputType || 'text'"
                                />
                                <span style="margin-left: 10px">
                                    <a-icon type="plus" @click="onClickPlus(key, i)" v-if="i === 0" />
                                    <a-icon type="minus" @click="onClickMinus(key, i)" v-if="i > 0" />
                                </span>
                            </div>
                        </div>
                        <div v-if="items.type === 'inputArrayJson'">
                            <div v-for="(vv, i) in form[key]" :key="i" class="input-array">
                                <a-input
                                    v-model="form[key][i]"
                                    :placeholder="`请输入${items.label}`"
                                    :type="items.inputType || 'text'"
                                />
                            </div>
                        </div>
                        <div v-if="items.type === 'inputObjectJson'">
                            <div v-for="(vv, i) in transformObject(form[key])" :key="i" class="input-array">
                                <div>
                                    <span>{{ vv }}:</span>
                                    <a-input
                                        v-model="form[key][vv]"
                                        :placeholder="`请输入${items.label}`"
                                        :type="items.inputType || 'text'"
                                    />
                                </div>
                            </div>
                        </div>
                        <a-select
                            v-else-if="items.type === 'select'"
                            v-model="form[key]"
                            :mode="items.mode || 'default'"
                            :maxTagCount="items.max || 3"
                            :placeholder="`请选择${items.label}`"
                            :showSearch="items.search || false"
                            @change="items.change"
                        >
                            <a-select-option
                                v-for="(value, i) in items.options"
                                :key="i"
                                :value="selectOptionsValue(value, items)"
                            >
                                {{ value.name || value[items.optionsLabel.name] }}
                            </a-select-option>
                        </a-select>
                        <a-tree-select
                            v-else-if="items.type === 'treeselect'"
                            v-model="form[key]"
                            :tree-data="items.options"
                            tree-checkable
                        />
                        <a-date-picker
                            v-else-if="items.type === 'date'"
                            v-model="form[key]"
                            :value-format="items.format || 'YYYY-MM-DD'"
                            :placeholder="`请选择${items.label}`"
                            style="width: 100%"
                        />
                        <a-date-picker
                            v-else-if="items.type === 'datetime'"
                            v-model="form[key]"
                            :value-format="items.format || 'YYYY-MM-DD HH:mm:ss'"
                            showTime
                            :placeholder="`请选择${items.label}`"
                            style="width: 100%"
                        />
                        <a-month-picker
                            v-else-if="items.type === 'month'"
                            v-model="form[key]"
                            :value-formt="items.format || 'MM'"
                            :placeholder="`请选择${items.label}`"
                            style="width: 100%"
                        />
                        <a-week-picker
                            v-else-if="items.type === 'week'"
                            v-model="form[key]"
                            :value-formt="items.format || 'WW'"
                            :placeholder="`请选择${items.label}`"
                            style="width: 100%"
                        />
                        <a-range-picker
                            v-else-if="items.type === 'datarange'"
                            v-model="form[key]"
                            :value-format="items.format || 'YYYY-MM-DD'"
                            :showTime="true"
                            style="width: 100%"
                        />
                        <a-time-picker
                            v-else-if="items.type == 'time'"
                            v-model="form[key]"
                            :value-format="items.format || 'HH:mm'"
                            :format="items.format || 'HH:mm'"
                            :hourStep="items.hourStep || 1"
                            :minuteStep="items.minuteStep || 1"
                            :placeholder="`请选择${items.label}`"
                            style="width: 100%"
                        />
                        <UploadImage
                            :path.sync="form[key]"
                            :images="items.images || []"
                            :multiple="items.multiple"
                            v-else-if="items.type === 'upload'"
                            :uploadType="items.uploadType || 'image'"
                            :size="items.size || 3"
                            :type="items.contentType || 'image/png,image/jpg,image/jpeg,image/gif'"
                        />
                        <QuillEditor v-if="items.type === 'editor'" :value.sync="form[key]" />
                        <a-radio-group
                            v-else-if="items.type === 'radio'"
                            :options="items.options"
                            v-model="form[key]"
                        />
                        <div v-if="items.type === 'number'" id="number">
                            <a-input-number
                                v-model="form[key].min"
                                :min="1"
                                :max="100000000"
                                :placeholder="`请输入${items.label}`"
                            />
                            <span>~</span>
                            <a-input-number
                                v-model="form[key].max"
                                :min="1"
                                :max="100000000"
                                :placeholder="`请输入${items.label}`"
                            />
                        </div>
                        <span v-if="items.desc" class="form-desc">{{ items.desc }}</span>
                    </a-form-model-item>
                </div>
            </a-form-model>
        </a-modal>
    </div>
</template>

<script>
import UploadImage from '@/components/UploadImage'
import QuillEditor from '@/components/Editor/QuillEditor'
import moment from 'moment'

export default {
    name: 'CommissionList',
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: ''
        },
        cancelText: {
            type: String,
            default: '取消'
        },
        okText: {
            type: String,
            default: '确认'
        },
        cancel: {
            type: Function,
            default: async () => {}
        },
        ok: {
            type: Function,
            default: async () => {}
        },
        width: {
            type: String,
            default: '520px'
        },
        closable: {
            type: Boolean,
            default: true
        },
        layout: {
            type: String,
            default: 'horizontal'
        },
        columns: {
            type: Object,
            default: () => {
                return {
                    // username 为data数据的key
                    // username: {
                    //     type: 'input',
                    //     label: '姓名',
                    //     备注
                    //     desc: ''
                    // },
                    // password: {
                    //     输入框
                    //     type: 'input',
                    //     label: '密码',
                    //     inputType 输入框类型
                    //     inputType: 'password'
                    // },
                    // roles: {
                    //     下拉选择
                    //     type: 'select',
                    //     label: '角色',
                    //     options 默认字段为 name value
                    //     options: [
                    //         {
                    //             name: '',
                    //             value: ''
                    //         }
                    //     ],
                    //     options 默认不为 name value 字段 请自行填写 name value的字段
                    //     optionsLabel: {
                    //         name: '',
                    //         value: ''
                    //     },
                    //      mode 默认default 可不传 'multiple' 'tags'
                    //     mode: 'default',
                    //     maxTagCount 默认为3 可不传 最多显示多少个 tag
                    //     maxTagCount: 3
                    // },
                    // mune: {
                    //     树形下拉选择
                    //     type: 'treeselect',
                    //     label: '角色'
                    // },
                    // date: {
                    //     日期组件
                    //     type: 'date',
                    //     label: '日期',
                    //     format 默认 YYYY-MM-DD 可不传 其他格式请看ant design date组件
                    //     format: 'YYYY-MM-DD'
                    // },
                    // datetime: {
                    // 日期组件 显示时分秒
                    //     type: 'datetime',
                    //     label: '时间',
                    // 见日期
                    //     format: 'YYYY-MM-DD HH:mm:ss'
                    // },
                    // month: {
                    // 日期组件 显示月份
                    //     type: 'month',
                    //     label: '月份',
                    //     format: 'MM'
                    // },
                    // week: {
                    // 日期组件 显示周
                    //     type: 'week',
                    //     label: '周',
                    //     format: 'WW'
                    // },
                    // daterange: {
                    // 日期组件 显示开始-结束 日期
                    //     type: 'daterange',
                    //     label: '日期联动',
                    //     format: 'YYYY-MM-DD',
                    //     show 默认false 可不传 是否显示 时分秒
                    //     show: false
                    // },
                    // time: {
                    // 日期组件 显示周
                    //     type: 'time',
                    //     label: '时间',
                    //     format: 'HH:mm',
                    //     hourStep: 1,
                    //     minuteStep: 1
                    // },
                    // editor: {
                    //     type: 'editor',
                    //     label: '富文本'
                    // }
                }
            }
        },
        data: {
            type: Object,
            default: () => {}
        },
        rules: {
            type: Object,
            default: () => {}
        },
        labelSpan: {
            type: Number,
            default: 3
        },
        wrapperSpan: {
            type: Number,
            default: 12
        }
    },
    components: {
        UploadImage,
        QuillEditor
    },
    watch: {
        data: {
            handler() {
                this.form = this.reset()
            },
            deep: true
        }
        // columns: {
        //     handler() {
        //         this.form = this.reset()
        //     },
        //     deep: true
        // }
    },
    data() {
        return {
            form: this.reset(),
            loading: false,
            moment
        }
    },
    methods: {
        selectOptionsValue(item, items) {
            if (item.value === 0 || item.value === '' || item.value) {
                return item.value
            }
            return item[items.optionsLabel.value]
        },
        transformObject(items) {
            if (items) {
                return Object.keys(items)
            }
            return []
        },
        onClickPlus(key, index) {
            this.form[key].push('')
        },
        onClickMinus(key, index) {
            this.form[key].splice(index, 1)
        },
        reset() {
            const form = {}
            Object.keys(this.columns).forEach(key => {
                if (
                    this.columns[key].type === 'datarange' ||
                    this.columns[key].type === 'treeselect' ||
                    this.columns[key].multiple ||
                    (this.columns[key].type === 'select' && this.columns[key].mode === 'multiple')
                ) {
                    form[key] = this.data[key] || this.columns[key].default || []
                } else if (this.columns[key].type === 'inputArray') {
                    form[key] = this.data[key] || this.columns[key].default || ['']
                } else if (this.columns[key].type === 'inputArrayJson') {
                    if (this.data[key]) {
                        form[key] = this.data[key].map(items => items.v)
                    } else {
                        form[key] = this.columns[key].default || ['']
                    }
                } else if (this.columns[key].type === 'number') {
                    const [start, end] = Array.isArray(this.data[key]) ? this.data[key] : []
                    form[key] = {
                        min: start ?? '',
                        max: end ?? ''
                    }
                } else {
                    form[key] =
                        this.data[key] || this.data[key] === 0 || this.data[key] === ''
                            ? this.data[key]
                            : this.columns[key].default
                                ? this.columns[key].default
                                : undefined
                }
                if (this.columns[key].type === 'upload' && this.data[key]) {
                    if (Array.isArray(this.data[key])) {
                        this.columns[key].images = this.data[key].map(items => {
                            return `${this.$url}/${items}`
                        })
                    } else {
                        this.columns[key].images = [`${this.$url}/${this.data[key]}`]
                    }
                } else if (this.columns[key].type === 'upload' && !this.data[key]) {
                    this.columns[key].images = []
                }
                if (this.columns[key].defaultValue) {
                    form[key] = this.columns[key].defaultValue
                }
            })
            console.log(form)
            return form
        },
        onClickCancel() {
            this.$emit('update:visible', false)
            this.$refs.form.clearValidate()
        },
        onClickOk() {
            this.loading = true
            this.$refs.form.validate(async valid => {
                if (valid) {
                    const form = this.filterData()
                    await this.$emit('update:data', form)
                    this.ok()
                        .then(() => {
                            this.$emit('update:visible', false)
                            this.$refs.form.clearValidate()
                            this.$refs.form.resetFields()
                        })
                        .finally(() => {
                            this.loading = false
                        })
                } else {
                    this.loading = false
                }
            })
        },
        filterData() {
            const result = {}
            Object.keys(this.form)
                .filter(key => this.form[key] !== '' && this.form[key] !== null && this.form[key] !== undefined)
                .forEach(key => {
                    if (this.columns[key].type === 'number') {
                        if (this.form[key].min && this.form[key].max) {
                            result[key] = [this.form[key].min, this.form[key].max]
                        }
                    } else {
                        result[key] = this.form[key]
                    }
                })
            return result
        }
    }
}
</script>

<style lang="less" scope>
.ant-modal-body {
    .input-array {
        display: flex !important;
        align-items: center !important;
    }
    .input-array + .input-array {
        margin-top: 10px;
    }
    .editor {
        .ant-form-item-control-wrapper {
            width: 100% !important;
        }
    }
    #number {
        display: inline-block;
        .ant-input-number {
            width: 100px;
        }
        span {
            padding: 0 5px;
        }
    }
}
.form-desc {
    font-size: 13px;
    color: #eb4641;
}
</style>
